//
//  LRDetailFamousViewController.m
//  本地生活圈
//
//  Created by admin on 15/8/15.
//  Copyright (c) 2015年 懒人. All rights reserved.
//

#import "LRDetailFamousViewController.h"
#import "LRHeaderView.h"
#import "LRFooterView.h"
#import "LRJudgeTableViewCell.h"
#import "LRMapViewController.h"
#import <MapKit/MapKit.h>
#import "LRShopComment.h"
#import "UMSocial.h"


@interface LRDetailFamousViewController ()<UITableViewDataSource,UITableViewDelegate,LRHeaderDelegate,LRFooterViewDelegate,UMSocialUIDelegate>
/**
 *  tableView
 */
@property (nonatomic, strong) UITableView *tableView;

/**
 *  尾部视图
 */
@property (nonatomic, strong) LRFooterView *footerView;

/**
 *  单击
 */
@property (nonatomic, strong) UITapGestureRecognizer *tap;

/**
 *  地理编码
 */
@property (nonatomic, strong) CLGeocoder *geocoder;
/**
 *  行高
 */
@property (nonatomic, assign) CGFloat heightForRow;
/**
 *  获取评论的页数
 */
@property (nonatomic, assign) int page;

@end

@implementation LRDetailFamousViewController

#pragma mark - Getter&Setter
- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kNavHeight, kUIScreenW, kUIScreenH - kNavHeight)]; // 或者修改tabbar的设置alpha为0 或移除原来的
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (CLGeocoder *)geocoder
{
    if (!_geocoder)
    {
        _geocoder = [[CLGeocoder alloc]init];
    }
    return _geocoder;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 初始化页面
    self.titleLabel.text = @"商家详情";
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.page = 2;
    
    // tableView头部视图
    self.headerView = [[NSBundle mainBundle] loadNibNamed:@"LRHeaderView" owner:nil options:nil].lastObject;
    self.headerView.detailModel = self.detail;
    self.headerView.delegate = self;
    self.headerView.frame = CGRectMake(0, 0, kUIScreenW, self.heightForHeader);
    self.tableView.tableHeaderView = self.headerView;
    
    // tableView尾部视图
    self.footerView = [[NSBundle mainBundle] loadNibNamed:@"LRFooterView" owner:nil options:nil].lastObject;
    
//    self.footerView.contentTextFile.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 0)];
//    self.footerView.contentTextFile.leftViewMode = UITextFieldViewModeAlways;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardTypeChangeWithNotifi:) name:UIKeyboardWillChangeFrameNotification object:nil];
//    self.footerView.contentTextFile.placeholder = @"textView??";
//    self.footerView.contentTextFile.adjustsFontSizeToFitWidth = YES;
    self.footerView.delegate = self;
    self.tableView.tableFooterView = self.footerView;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 隐藏tabbar
    UIApplication *app = [UIApplication sharedApplication];
    LRTabBarViewController *tabBar = (LRTabBarViewController *)app.keyWindow.rootViewController;
    tabBar.tabBarView.hidden = YES;
}

#pragma mark - 键盘实现
// 监听键盘出现及回收（frame改变）的方法 NSNotification的分类继承NSNotificationCenter
- (void)keyboardTypeChangeWithNotifi:(NSNotification *)notifi
{
    // 将底部的window颜色改，否则有可能出现黑色
    self.view.window.backgroundColor = self.view.backgroundColor;
    CGFloat upY = [notifi.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue].origin.y - kUIScreenH;
    
    // 采用动画
    [UIView animateWithDuration:[notifi.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] floatValue] animations:^{
//        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        [self.tableView setScrollsToTop:YES];
        // 设置view的frame
        self.view.transform = CGAffineTransformMakeTranslation(0,upY);
    }];
}
// 拖动tableview 结束编辑
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}
// 单击屏幕停止编辑


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource&Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.detail.comment_list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentier = @"LRJudgeTableViewCell";
    LRJudgeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentier];
    if (!cell)
    {
        cell = [[NSBundle mainBundle]loadNibNamed:indentier owner:nil options:nil].lastObject;
    }
//    NSLog(@"%@",NSStringFromCGRect(cell.frame));
    cell.list = self.detail.comment_list[indexPath.row];
    self.heightForRow = cell.cellHeight;
    return cell;
}

// 加载更多
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    // 如果评论页数少于2页不需要加载
    if (self.detail.comment_totalPage < 2) return nil;

    UIView *moreView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUIScreenW, kUITableViewSectionHeaderHeight)];
    moreView.backgroundColor = [UIColor blackColor];
    moreView.alpha = 0.3;
    UIButton *btn = [[UIButton alloc]initWithFrame:moreView.bounds];
    [btn addTarget:self action:@selector(getMore) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:@"查看更多评论" forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"cirlce_drop"] forState:UIControlStateNormal];
    [moreView addSubview:btn];
    
    return moreView;
}

// 加载更多评论数据
- (void)getMore
{
    // 获取数据
    NSString *detailStr = @"http://www.qd-life.com/api/1/comment/get_comment_list";
    
    // 参数设置
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@"shop" forKey:@"res_name"];
    NSString *Id = [NSString stringWithFormat:@"%zd",self.detail.id];
    [params setObject:Id forKey:@"res_id"];
    NSString *num = [NSString stringWithFormat:@"%d",self.page];
    [params setObject:num forKey:@"page"];
    [params setObject:[LRFunction getTimeScamp] forKey:@"time"];
    NSArray *arr = @[APP_ID,params[@"res_name"],params[@"res_id"],params[@"page"],params[@"time"],APP_IDENGER];
    [params setObject:[LRFunction md5StringFromArray:arr] forKey:@"sign"];
    [params setObject:APP_ID forKey:@"app_id"];
    
    [self.manager POST:detailStr parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        id result = responseObject[@"status"];
        if ([result isEqualToString:@"error"])
        {
            [MBProgressHUD showError:[NSString stringWithFormat:@"%@",responseObject[@"error_info"]]];
            return ;
        }
        
        // 解析数据模型

        LRShopComment *comment = [[LRShopComment alloc]initWithDictionary:responseObject error:nil];
        for (int i = 0; i < comment.list.count; i++)
        {
            [self.detail.comment_list addObject:comment.list[i]];
        }
        [self.tableView reloadData];
        self.page +=2;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        LRLog(@"%@",error);
    }];
}

// 尾部视图高度
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section
{
    if (self.detail.comment_totalPage < 2 || self.page >= self.detail.comment_totalPage) return 0;
    return kUITableViewSectionHeaderHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.heightForRow;
}

// 必须实现高度才能出来头部
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kUITableViewSectionHeaderHeight;
}

// 表头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUIScreenW, kUITableViewSectionHeaderHeight)];
    view.backgroundColor = [UIColor whiteColor];
    
    //添加上分割线
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUIScreenW, 5)];
    line.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:line];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 6, kUIScreenW - 10, kUITableViewSectionHeaderHeight - 6)];
 
    titleLabel.text = @"用户评价";

    titleLabel.font = [UIFont fontWithName:@"Menlo" size:20];
    [titleLabel setTextColor:[UIColor redColor]];
    titleLabel.textAlignment = NSTextAlignmentLeft;
    [view addSubview:titleLabel];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, kUITableViewSectionHeaderHeight - 1, kUIScreenW, 1)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:lineView];

    return view;
}


#pragma mark - LRHeaderDelegate
// 打电话
- (void)headerCallPhoneWithPhone:(NSString *)phone
{
    UIAlertController *alertVc = [[UIAlertController alloc]init];
    
    UIAlertAction *callAc = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"%@",phone] style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        
        NSMutableString *str = [[NSMutableString alloc]initWithFormat:@"telprompt://%@",phone];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"模拟器打毛"];
        });
    }];
    
    UIAlertAction *cancelAc = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        return ;
    }];
    
    [alertVc addAction:callAc];
    [alertVc addAction:cancelAc];
    [self presentViewController:alertVc animated:YES completion:nil];
}

// 分享
- (void)headerShare
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:AppUmKey
                                      shareText:@"你要分享的文字:"
                                     shareImage:[UIImage imageNamed:@"home_error"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToTencent,UMShareToQzone,nil]
                                       delegate:self];
}

// 地图定位
- (void)locationUpdateWithAdress:(NSString *)adress
{
//    LRMapViewController *map = [[LRMapViewController alloc] init];
//    
//    [self.navigationController pushViewController:map animated:YES];
//    [MBProgressHUD showError:@"百度地图有bug待测试"];
    
    // 解码地址
    [self.geocoder geocodeAddressString:adress completionHandler:^(NSArray *placemarks, NSError *error) {
        
        CLPlacemark *mark = placemarks.lastObject;
//        MKPlacemark *startMk = [[MKPlacemark alloc]initWithPlacemark:mark];
//        MKMapItem *item = [[MKMapItem alloc]initWithPlacemark:startMk];
        
//        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        
//        dict[MKLaunchOptionsDirectionsModeKey] = MKLaunchOptionsDirectionsModeDriving;
//        [MKMapItem openMapsWithItems:@[item] launchOptions:dict];
        
        // 采用在app上打开地图
        LRMapViewController *map = [[LRMapViewController alloc]init];
        map.placeMark = mark;
        map.adress = adress;
        [self.navigationController pushViewController:map animated:YES];
    }];
}

#pragma mark - LRFooterViewDelegate
- (void)footerSendWithCont:(NSString *)cont score:(NSString *)score
{
    NSString *detailStr = @"http://www.qd-life.com/api/1/comment/commit_comment";
    // 参数设置www.qd-life.com/api/1/comment/get_comment_list
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    //[[LRUserInfo shareInstance] user_id]
    [params setObject:@"600" forKey:@"user_id"];
    [params setObject:cont forKey:@"cont"]; // 内容是加密的？
    [params setObject:[LRFunction getTimeScamp] forKey:@"time"];
    [params setObject:@"shop" forKey:@"res_name"];
    [params setObject:score forKey:@"score"];
    NSString *Id = [NSString stringWithFormat:@"%zd",self.detail.id];
    [params setObject:Id forKey:@"res_id"];
    NSArray *arr = @[APP_ID,params[@"user_id"],params[@"res_name"],params[@"res_id"],params[@"score"],params[@"time"],APP_IDENGER];
    [params setObject:[LRFunction md5StringFromArray:arr] forKey:@"sign"];
    [params setObject:APP_ID forKey:@"app_id"];
    
    self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];

    [self.manager POST:detailStr parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            // 刷新数据
        [self getMore];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD showError:@"Cocoa error 3840,暂时保存沙盒"];
            NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
            NSString *filePath = [path stringByAppendingPathComponent:@"info.dog"];
            [params writeToFile:filePath atomically:YES];
        
    }];

}



@end
